package com.soxing.webrain.brush.service.webSocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/websocket/{type}")  // ws://localhost:8080/websocket
@Component
public class WebSocketServer {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketServer.class);

    private Session session;
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();

    private String type;

    // TODO 实验到一半websocket断了又重连会怎么样
    @OnOpen
    public void onOpen(Session session, @PathParam("type") String type) {
        this.type = type;
        String msg;
        switch (type) {
            case "docker":
                msg = "docker日志交互";
                break;
            case "data":
                msg = "采集客户端交互";
                break;
            default:
                msg = "未知来源，拒绝连接";
                logger.info(msg);
                return;
        }
        logger.info("连接成功：" + msg);
        this.session = session;
        webSocketSet.add(this);
    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
    }

    @OnMessage
    public void onMessage(String message, Session session,  @PathParam("type") String type) {
        logger.info("接收到" + type + "数据" + message);
        // 可以处理前端发送的消息
        switch (type) {
            case "data":
                if(message == "以休伯利安的名义") {
                    // TODO 应该在controller那边加个监听，多少时间内回复指定内容才算连接上了
                }
                break;
            default:
                return;
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    // 用于将 Docker 日志发送到前端的方法
    public static void sendMessage(String message, String targetType) {
        for (WebSocketServer item : webSocketSet) {
            if(item.type.equals(targetType)) {
                try {
                    item.session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public boolean hasType(String type) {
        return webSocketSet.stream()
                .anyMatch(item -> item.type.equals(type));
    }

    public static void sendDockerLog(String message) {
        sendMessage(message, "docker");
    }

    public static void sendDateFlag(String message) {
        sendMessage(message, "data");
    }
}
